package com.example.todolist.util

import android.Manifest
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresPermission
import com.example.todolist.database.model.TodoEntity
import com.example.todolist.receiver.NotificationReceiver
import kotlin.jvm.java

object AlarmUtils {
    fun setExactAlarm(
        context: Context,
        timeInMillis: Long,
        todo: TodoEntity
    ) {
        val title = todo.title
        val content = todo.detail
        val todoId = todo.id
        val requestCode = todo.id
        val alarmManager = context.getSystemService(AlarmManager::class.java)
        val intent = Intent(context, NotificationReceiver::class.java).apply {
            putExtra("title", "待办截止提醒")
            putExtra("content", "${title}:$content")
            putExtra("todoId", todoId)
        }
        val pendingIntent = PendingIntent.getBroadcast(
            context,
            requestCode, // 请求码（用于区分不同闹钟）
            intent,
            PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        // API 31+ 需使用 setExactAndAllowWhileIdle
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                timeInMillis,
                pendingIntent
            )
        } else
            alarmManager.setExact(
                AlarmManager.RTC_WAKEUP,
                timeInMillis,
                pendingIntent
            )
    }

    /**
     * 用户更新提醒时间的时候用得到
     */
    fun cancelAlarm(context: Context) {
        val alarmManager = context.getSystemService(AlarmManager::class.java)
        val intent = Intent(context, NotificationReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_IMMUTABLE
        )
        alarmManager.cancel(pendingIntent)
    }
}